import React, { useState } from 'react'
import LoginCss from './index.module.css'
import { Input,Button,message} from 'antd';
import { UserOutlined,LockOutlined} from '@ant-design/icons';
import {useNavigate} from 'react-router-dom';
import {useDispatch} from 'react-redux'
// 引入封装登录接口
import userLogin from '../../api/login';
// 引入封装表单自定义hooks
import useInput from '../../hooks/useInput';
import tokenAction from '../../redux/action/tokenAction';
export default function Login() {
    let navigate = useNavigate();
    // 定义按钮加载状态
    let [loading,setLoading] = useState(false);
    let username = useInput();
    let password = useInput();
    let dispatch = useDispatch();
    // 用户登录
    let Login =async ()=>{
        console.log(username.value);
        console.log(password.value)
        if(!username.value || !password.value){
            message.warning("请您补充完整信息！")
            return;
        }
        setLoading(true);
        // 发送请求
        let res = await userLogin({
            username:username.value,
            password:password.value
        });
        setLoading(false);
        if(res.data.meta.status!==200 && res.data.meta.status!==201 && res.data.meta.status!==204){
            return
        }
        // 登录成功 将token存储到本地
        localStorage.setItem("token",res.data.data.token);
        // 触发dispatch 将token存储到redux
        dispatch(tokenAction(res.data.data.token));
        // 跳转到首页
        navigate('/')
    }
  return (
    <div className={LoginCss.login}>
        <div className={LoginCss.box}>
            <div className={LoginCss.title}>用户登录</div>
            <div className={LoginCss.inpt}>
            <Input size="middle" placeholder="请输入用户名" prefix={<UserOutlined />} {...username}/>
            </div>
            <div className={LoginCss.inpt}>
            <Input.Password size="middle" placeholder="请输入密码" prefix={<LockOutlined />} {...password} onPressEnter={Login}/>
            </div>
            <div className={LoginCss.inpt}>
                <Button block type='primary' onClick={Login} loading={loading}>登录</Button>
            </div>
        </div>
    </div>
  )
}
